package com.otp.service.impl;

import com.otp.exception.BusinessException;
import com.otp.pojo.entity.Course;
import com.otp.pojo.request.course.*;
import com.otp.repository.CourseJoinRepository;
import com.otp.repository.CourseRepository;
import com.otp.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private CourseJoinRepository courseJoinRepository;

    @Override
    public List<Course> list() {
        return courseRepository.findAll();
    }

    @Override
    public List<Course> listByTeacherId(Long teacherId) {
        return courseRepository.findByTeacherId(teacherId);
    }

    @Override
    public List<Course> listByStatus(String status) {
        return courseRepository.findByStatus(status);
    }

    @Override
    public Course getById(Long id) {
        return courseRepository.findById(id)
                .orElseThrow(() -> new BusinessException("课程不存在"));
    }

    @Override
    public Course create(CourseCreateRequest request) {
        Course course = new Course();
        BeanUtils.copyProperties(request, course);
        course.setStatus("APPROVED");
        return courseRepository.save(course);
    }

    @Override
    public Course update(CourseUpdateRequest request) {
        Course course = courseRepository.findById(request.getId())
                .orElseThrow(() -> new BusinessException("课程不存在"));
        BeanUtils.copyProperties(request, course);
        return courseRepository.save(course);
    }

    @Override
    public void delete(Long id) {
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new BusinessException("课程不存在"));
        courseRepository.delete(course);
    }
}